package com.sduept.nwld.dataserver.rest;

import com.sduept.bigdata.fault.common.ParamDesc;
import com.sduept.bigdata.fault.protection.model.*;
import com.sduept.bigdata.fault.protection.service.ProtectChannelAlarmQueryManager;
import com.sduept.bigdata.fault.protection.service.ProtectDeviceAlarmQueryManager;
import com.sduept.bigdata.weather.map.MapDataCache;
import com.sduept.cim.model.core.Substation;
import com.sduept.cim.model.extend.LineTower;
import com.sduept.cim.model.protection.ProtectionEquipment;
import com.sduept.core.ParamManager;
import com.sduept.core.dao.SuperDAO;
import com.sduept.nwld.dataserver.manager.protection.ProtectStatusManager;
import com.sduept.utils.DateUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.util.*;
import java.util.Map.Entry;
@RestController
@RequestMapping("/protectAlarm/")
public class ProtectAlarmService {
	@Autowired
	private SuperDAO dao;
	@Autowired
	private ProtectChannelAlarmQueryManager pm;
	@Autowired
	private MapDataCache cc;
	@Autowired
	private ProtectDeviceAlarmQueryManager pdam;
	@Autowired
	private ProtectStatusManager psm;
	@Autowired
	private ParamManager pc;

	
	@GetMapping("/getProtectionDeviceStatusByTime/{time}")
	public String getProtectionDeviceStatusByTime(@PathVariable("time") String time) {
		Date t = DateUtil.getDateByString(time, DateUtil.pattern_ymdhms);
		Calendar c = Calendar.getInstance();
		c.add(Calendar.DAY_OF_YEAR, -1);
		List<ProtectDeviceAlarm> deviceProtects = dao
				.findByCondition(
						ProtectDeviceAlarm.class,
						"protectType like '主%' and eventStart>= ? and eventStart <= ? and (revertTime>= ? or revertTime is null)",
						c.getTime(), t, t);
		HashMap<String, Substation> stationMap = cc.getStationid_map();
		Map<String, Integer> stations = new HashMap<>();
		HashSet<String> protectIds = new HashSet<>();
		for (ProtectDeviceAlarm dp : deviceProtects) {
			String stationId = dp.getStationId();
			Substation s = stationMap.get(stationId);
			String key = s.getLongitude() + "," + s.getLatitude() + "," + s.getId() + "," + s.getName();
			Integer count = stations.get(key);
			if (count == null) {
				stations.put(key, 1);
			} else {
				stations.put(key, count + 1);
			}
			protectIds.add(dp.getProtectId());
		}
		JSONObject result = new JSONObject();
		result.put("alarmProtectionNum", protectIds.size());
		result.put("allNum", dao.count(" type like ? or standvoltage > 499 ", new Object[] { "主%" },
				ProtectionEquipment.class));
		result.put("stations", stations);
		result.put("alarms", deviceProtects);
		return result.toString();
	}

	
	@GetMapping("/getProtectChannelAlarm/{start}/{end}")
	public String getProtectChannelAlarm(@PathVariable("start") String start, @PathVariable("end") String end) {
		Date s = DateUtil.getDateByString(start, DateUtil.pattern_ymd);
		Date e = DateUtil.getDateByString(end, DateUtil.pattern_ymd);
		Calendar c = Calendar.getInstance();
		c.setTime(e);
		c.add(Calendar.DAY_OF_YEAR, 1);
		e = c.getTime();
		List<ProtectChannelAlarm> alarms = pm.getAllProtectChannelAlarm(s, e);
		Map<String, Substation> stations = cc.getStationid_map();
		JSONArray result = new JSONArray();
		for (ProtectChannelAlarm a : alarms) {
			JSONObject o = JSONObject.fromObject(a);
			Substation station = stations.get(a.getStationId());
			o.put("lon", station == null ? "" : station.getLongitude());
			o.put("lat", station == null ? "" : station.getLatitude());
			result.add(o);
		}
		return result.toString();
	}

	/**
	 * 保护告警模块-----地图使用的中断告警，添加了lon，lat字段
	 *
	 * @param start
	 * @param end
	 * @return
	 */
	
	@GetMapping("/getMapProtectInterruptAlarm/{start}/{end}")
	public String getMapProtectInterruptAlarm(@PathVariable("start") String start, @PathVariable("end") String end) {
		Date s = DateUtil.getDateByString(start, DateUtil.pattern_ymd);
		Date e = DateUtil.getDateByString(end, DateUtil.pattern_ymd);
		Calendar c = Calendar.getInstance();
		c.setTime(e);
		c.add(Calendar.DAY_OF_YEAR, 1);
		e = c.getTime();
		List<ProtectInterruptAlarm> interrupts = pdam.getProtectInterruptAlarmByStationAndDate(null, s, e);
		JSONArray interruptJson = new JSONArray();
		HashMap<String, Substation> stationIdMap = cc.getStationid_map();
		for (ProtectInterruptAlarm o : interrupts) {
			JSONObject jo = JSONObject.fromObject(o);
			Substation st = stationIdMap.get(o.getStationId());
			if (st != null) {
				jo.put("lon", st.getLongitude());
				jo.put("lat", st.getLatitude());
			}
			interruptJson.add(jo);
		}
		return interruptJson.toString();
	}

	/**
	 * 保护告警模块----明细使用的中断告警
	 *
	 * @param start
	 * @param end
	 * @return
	 */
	
	@GetMapping("/getProtectInterruptAlarm/{start}/{end}")
	public String getProtectInterruptAlarm(@PathVariable("start") String start, @PathVariable("end") String end) {
		Date startDate = DateUtil.getDateByString(start, DateUtil.pattern_ymd);
		Date endDate = DateUtil.getDateByString(end, DateUtil.pattern_ymd);
		Calendar c = Calendar.getInstance();
		c.setTime(endDate);
		c.add(Calendar.DAY_OF_YEAR, 1);
		c.add(Calendar.SECOND, -1);
		endDate = c.getTime();
		List<ProtectInterruptAlarm> interrupts = pdam.getProtectInterruptAlarmByStationAndDate(null,
				startDate, endDate);
		return JSONArray.fromObject(interrupts).toString();
	}

	/**
	 * 保护告警模块----明细使用的中断告警(懒加载模式)
	 *
	 * @param stationId
	 * @param sdate
	 * @param edate
	 * @param sEcho
	 * @param iDisplayStart
	 * @param iDisplayLength
	 * @return JSONObject res
	 */
	
	@GetMapping("/getProtectInterruptAlarmDetails/{params}")
	public String getProtectInterruptAlarmDetails(@PathVariable("params") String params) {
		JSONArray array = JSONArray.fromObject(params);
		int n = ((JSONObject) array.get(3)).getInt("value");
		int m = ((JSONObject) array.get(4)).getInt("value");
		String stationId = ((JSONObject) array.get(13)).getString(("value"));
		// paramList：开始时间，结束时间，线路列表，变电站列表，电压列表，原因列表
		List<String[]> paramList = getStringObject(array);
		Date startDate = DateUtil.getDateByString(paramList.get(0)[0], DateUtil.pattern_ymd);
		Date endDate = DateUtil.getDateByString(paramList.get(1)[0], DateUtil.pattern_ymd);
		Calendar c = Calendar.getInstance();
		c.setTime(endDate);
		c.add(Calendar.DAY_OF_YEAR, 1);
		c.add(Calendar.SECOND, -1);
		endDate = c.getTime();
		List<Object> param = new ArrayList<Object>();
		param.add(startDate);
		param.add(endDate);
		param.add(paramList);//paramList:线路列表，变电站列表，电压列表，原因列表
		param.add(1);//sEcho
		param.add(n);//iDisplayStart
		param.add(m);//iDisplayLength
		param.add(stationId);
		List<ProtectInterruptAlarm> interrupts = pdam.getProtectInterruptAlarmByStationAndDate(param);
		long count = pdam.getDataCount(param);
		String[] reasons = paramList.get(5);
		List<ProtectInterruptAlarm> reasult = new ArrayList<ProtectInterruptAlarm>();
		if (reasons.length == 1 && !reasons[0].equals("")) {
			if (reasons[0].equals("device")) {
				for (ProtectInterruptAlarm p : interrupts) {
					if (p.getChannelAlarms().size() > 0) {
						reasult.add(p);
					}
				}
			} else if (reasons[0].equals("channel")) {
				for (ProtectInterruptAlarm p : interrupts) {
					if (p.getChannelAlarms().size() == 0) {
						reasult.add(p);
					}
				}
			}
		} else {
			reasult = interrupts;
		}
		for (int p = 0; p < reasult.size(); p++) {
			ProtectInterruptAlarm pro = reasult.get(p);
			pro.setSort(n + p + 1);
		}
		JSONObject res = new JSONObject();
		res.put("aaData", reasult);
		res.put("recordsTotal", count);
		res.put("recordsFiltered", count);
		return res.toString();
	}

	/**
	 * 为getProtectInterruptAlarm方法，将JSONArray转化为可用参数
	 *
	 * @param array
	 * @return
	 */
	private List<String[]> getStringObject(JSONArray array) {
		// 开始时间，结束时间，线路列表，变电站列表，电压列表，原因列表
		List<String[]> paramList = new ArrayList<String[]>();
		int i = array.size();
		for (int j = 6; j > 0; j--) {
			JSONObject obj = (JSONObject) array.get(i - j);
			String str = obj.getString("value");
			String[] strArray = str.split(",");
			paramList.add(strArray);
		}
		return paramList;
	}

	/**
	 * 保护告警模块-----变电站的中断告警弹窗
	 *
	 * @param start
	 * @param end
	 * @param stationId
	 * @return
	 */
	
	@GetMapping("/getProtectInterruptAlarmByStationId/{start}/{end}/{stationId}")
	public String getProtectInterruptAlarmByStationId(@PathVariable("start") String start,
			@PathVariable("end") String end, @PathVariable("stationId") String stationId) {
		Date startDate = DateUtil.getDateByString(start, DateUtil.pattern_ymd);
		Date endDate = DateUtil.getDateByString(end, DateUtil.pattern_ymd);
		Calendar c = Calendar.getInstance();
		c.setTime(endDate);
		c.add(Calendar.DAY_OF_YEAR, 1);
		endDate = c.getTime();
		List<ProtectInterruptAlarm> interrupts = pdam.getProtectInterruptAlarmByStationAndDate(stationId,
				startDate, endDate);
		return JSONArray.fromObject(interrupts).toString();
	}

	/**
	 * 保护告警模块-----地图使用的保护通道频繁中断
	 *
	 * @param start
	 * @param end
	 * @return
	 */
	
	@GetMapping("/getMapFrequentProtectInterruptAlarm/{start}/{end}")
	public String getMapFrequentProtectInterruptAlarm(@PathVariable("start") String start,
			@PathVariable("end") String end) {
		Date s = DateUtil.getDateByString(start, DateUtil.pattern_ymd);
		Date e = DateUtil.getDateByString(end, DateUtil.pattern_ymd);
		Map<String, TreeSet<LineTower>> ltMap = cc.getLtmap500();
		Calendar c = Calendar.getInstance();
		c.setTime(e);
		c.add(Calendar.DAY_OF_YEAR, 1);
		e = c.getTime();
		List<ProtectDeviceAlarmModel> frequentInterrupts = pdam
				.getFrequentProtectInterruptAlarmByStationAndDate(null, s, e);
		JSONArray result = new JSONArray();
		for (ProtectDeviceAlarmModel f : frequentInterrupts) {
			TreeSet<LineTower> towers = ltMap.get(f.getLineId());
			if (towers == null) {
				result.add(f);
			} else {
				JSONObject o = JSONObject.fromObject(f);
				o.put("lon", towers.first().getLongitude());
				o.put("lat", towers.first().getLatitude());
				result.add(o);
			}
		}
		return result.toString();
	}

	/**
	 * 保护告警模块-----弹窗使用的保护通道频繁中断
	 *
	 * @param start
	 * @param end
	 * @return
	 */
	
	@GetMapping("/getFrequentProtectInterruptAlarm/{start}/{end}/{param1}/{param2}")
	public String getFrequentProtectInterruptAlarm(@PathVariable("start") String start,
			@PathVariable("end") String end, @PathVariable("param1") Integer param1,
			@PathVariable("param2") Integer param2) {
		Date s = DateUtil.getDateByString(start, DateUtil.pattern_ymd);
		Date e = DateUtil.getDateByString(end, DateUtil.pattern_ymd);
		Calendar c = Calendar.getInstance();
		c.setTime(e);
		c.add(Calendar.DAY_OF_YEAR, 1);
		c.add(Calendar.SECOND, -1);
		e = c.getTime();
		List<ProtectDeviceAlarmModel> frequentInterrupts = pdam
				.getFrequentProtectInterruptAlarmByStationAndDate(null, s, e, param2, param1 * 60000);
		Collections.sort(frequentInterrupts, new Comparator<ProtectDeviceAlarmModel>() {
			@Override
			public int compare(ProtectDeviceAlarmModel o1, ProtectDeviceAlarmModel o2) {
				return o2.getAlarms().size() - o1.getAlarms().size();
			}
		});

		return JSONArray.fromObject(frequentInterrupts).toString();
	}

	
	@GetMapping("/getFrequentProtectInterruptAlarmParams")
	public Integer[] getFrequentProtectInterruptAlarmParams() {
		Integer minCount = Integer.parseInt(pc.get(ParamDesc.FREQUENTLY_DEVICE_ALARM_MIN_COUNT).getValue());
		Integer maxTime = Integer.parseInt(pc.get(ParamDesc.FREQUENTLY_DEVICE_ALARM_TIME_MAX_GAP).getValue());
		return new Integer[] { maxTime / 60000, minCount };
	}

	/**
	 * 保护告警模块-----地图上使用的保护双通道相继异常 ,暂时不添加地理位置字段
	 *
	 * @param start
	 * @param end
	 * @return
	 */
	
	@GetMapping("/getMapFrequentDoubleChannelAlarm/{start}/{end}")
	public String getMapFrequentDoubleChannelAlarm(@PathVariable("start") String start,
			@PathVariable("end") String end) {
		Date s = DateUtil.getDateByString(start, DateUtil.pattern_ymd);
		Date e = DateUtil.getDateByString(end, DateUtil.pattern_ymd);
		Map<String, TreeSet<LineTower>> ltMap = cc.getLtmap500();
		Calendar c = Calendar.getInstance();
		c.setTime(e);
		c.add(Calendar.DAY_OF_YEAR, 1);
		e = c.getTime();
		List<ProtectDeviceAlarmModel> channels = pdam.getFrequentDoubleInterruptAlarmByDate(null, s, e);
		JSONArray result = new JSONArray();
		for (ProtectDeviceAlarmModel f : channels) {
			TreeSet<LineTower> towers = ltMap.get(f.getLineId());
			if (towers == null || towers.size() == 0) {
				result.add(f);
			} else {
				JSONObject o = JSONObject.fromObject(f);
				o.put("lon", towers.first().getLongitude());
				o.put("lat", towers.first().getLatitude());
				result.add(o);
			}
		}
		return result.toString();
	}

	/**
	 * 保护告警模块-----弹窗使用的保护双通道相继异常
	 *
	 * @param start
	 * @param end
	 * @return
	 */
	
	@GetMapping("/getFrequentDoubleChannelAlarm/{start}/{end}")
	public String getFrequentDoubleChannelAlarm(@PathVariable("start") String start, @PathVariable("end") String end) {
		JSONArray result = new JSONArray();
		Integer maxTime = Integer.parseInt(pc.get(ParamDesc.FREQUENTLY_DOUBLE_CHANNEL_ALARM_TIME_MAX_GAP)
				.getValue());
		Date s = DateUtil.getDateByString(start, DateUtil.pattern_ymd);
		Date e = DateUtil.getDateByString(end, DateUtil.pattern_ymd);
		Calendar c = Calendar.getInstance();
		c.setTime(e);
		c.add(Calendar.DAY_OF_YEAR, 1);
		c.add(Calendar.SECOND, -1);
		e = c.getTime();
		List<ProtectDeviceAlarmModel> channels = pdam.getFrequentDoubleInterruptAlarmByDate(null, s, e);
		// 添加双通道告警附近的频繁告警
		List<ProtectInterruptAlarm> list = pdam.getProtectInterruptAlarmByStationAndDate(null, s, e);
		Iterator<ProtectDeviceAlarmModel> it = channels.iterator();
		Iterator<ProtectInterruptAlarm> lit = list.iterator();
		while (it.hasNext()) {
			ProtectDeviceAlarmModel model = it.next();
			List<AbstractProtectAlarm> as = model.getAlarms();
			// 若发生了双通道同时中断，将双通道中断前后半小时内的中断全部放到alarms
			long starttime = as.get(0).getEventStart().getTime() - maxTime;
			long endtime = as.get(as.size() - 1).getEventStart().getTime() + maxTime;
			lit = list.iterator();
			List<AbstractProtectAlarm> frequentAlarms = new ArrayList<>();
			while (lit.hasNext()) {
				AbstractProtectAlarm a = lit.next();
				long t = a.getEventStart().getTime();
				if (a.getLineId() != null && a.getLineId().equals(model.getLineId())
						&& a.getProtectType() != null && a.getProtectType().equals(model.getProtectType())
						&& t > starttime && t < endtime) {
					frequentAlarms.add(a);
				}
			}
			Collections.sort(frequentAlarms, new Comparator<AbstractProtectAlarm>() {
				@Override
				public int compare(AbstractProtectAlarm o1, AbstractProtectAlarm o2) {
					Long t1 = o1.getEventStart().getTime() + o1.getmStartMs();
					Long t2 = o2.getEventStart().getTime() + o2.getmStartMs();
					return t1.compareTo(t2);
				}
			});
			JSONObject o = JSONObject.fromObject(model);
			o.put("frequentAlarms", frequentAlarms);
			result.add(o);
		}
		return result.toString();
	}

	/**
	 * 保护状态模块-----原变电站的装置告警弹窗
	 *
	 * @param start
	 * @param end
	 * @param stationId
	 * @return
	 * @throws ParseException
	 */
	
	@GetMapping("/getProtectDeviceAlarmByStationId/{start}/{end}/{stationId}")
	public String getProtectDeviceAlarmByStationId(@PathVariable("start") String start,
			@PathVariable("end") String end, @PathVariable("stationId") String stationId) throws ParseException {
		String startStr = start + " 00:00:00";
		String endStr = end + " 23:59:59";
		List<ProtectDeviceAlarm> devices = pdam.getProtectDeviceAlarmByStationId(new String[] { stationId },
				startStr, endStr);
		return JSONArray.fromObject(devices).toString();
	}

	
	@GetMapping("/getProtectDeviceAlarmByTime/{time}")
	public String getProtectDeviceAlarmByTime(@PathVariable("time") String time) {
		Date t = DateUtil.getDateByString(time, DateUtil.pattern_ymdhms);
		Calendar c = Calendar.getInstance();
		c.add(Calendar.DAY_OF_YEAR, -1);
		List<ProtectDeviceAlarm> deviceProtects = dao
				.findByCondition(
						ProtectDeviceAlarm.class,
						"protectType like '主%' and eventStart>= ? and eventStart <= ? and (revertTime>= ? or revertTime is null)",
						c.getTime(), t, t);
		return JSONArray.fromObject(deviceProtects).toString();
	}

	
	@GetMapping("/getProtectionStatusByStationId/{stationId}")
	public String getProtectionStatusByStationId(@PathVariable("stationId") String stationId) {
		// [protectionNum:,alarmStations:[{stationName:,stationId:,longitude,latitude,alarmProtections:[name:,station:]},{}]
		List<ProtectionEquipment> protects = psm.getProtectStatusByStationId(stationId);
		return JSONArray.fromObject(protects).toString();
	}

	// 保护状态通讯异常获取详细信息
	
	@GetMapping("/getChannelStatusByPrivateId/{privateId}")
	public String getChannelStatusByPrivateId(@PathVariable("privateId") String privateId) {
		ProtectChannelAlarm status = pm.getProtectChannelAlarm(privateId);
		return JSONArray.fromObject(status).toString();
	}

	// 保护状态运行异常获取详细信息
	
	@GetMapping("/getDevidesStatusByPrivateId/{privateId}")
	public String getDevidesStatusByPrivateId(@PathVariable("privateId") String privateId) {
		ProtectDeviceAlarm status = pdam.getProtectDeviceAlarm(privateId);
		return JSONArray.fromObject(status).toString();
	}

	
	@GetMapping("/getProtectAlarmsByStartAndEnd/{start}/{end}")
	public String getProtectAlarmsByStartAndEnd(@PathVariable("start") String start, @PathVariable("end") String end) {
		Date s = DateUtil.getDateByString(start, DateUtil.pattern_ymdhms);
		Date e = DateUtil.getDateByString(end, DateUtil.pattern_ymdhms);
		List<AbstractProtectAlarm> alarms = new ArrayList<AbstractProtectAlarm>();
		alarms.addAll(dao
				.findByCondition(
						ProtectInterruptAlarm.class,
						"eventStart between ? and ? or revertTime between ? and ? or (eventStart<? and (revertTime>? or revertTime is null)) ",
						s, e, s, e, s, s));
		alarms.addAll(dao
				.findByCondition(
						ProtectDeviceAlarm.class,
						" eventStart between ? and ? or revertTime between ? and ? or (eventStart<? and (revertTime>? or revertTime is null)) ",
						s, e, s, e, s, s));
		HashMap<String, Substation> stationMap = cc.getStationid_map();
		JSONArray alarmsJson = new JSONArray();
		for (AbstractProtectAlarm d : alarms) {
			Substation station = stationMap.get(d.getStationId());
			if (station == null) {
				alarmsJson.add(d);
			} else {
				JSONObject o = JSONObject.fromObject(d);
				o.put("lon", station.getLongitude());
				o.put("lat", station.getLatitude());
				alarmsJson.add(o);
			}
		}
		return alarmsJson.toString();
	}

	/**
	 * 懒加载-获取查询线路内容
	 *
	 * @param start
	 * @param end
	 * @return
	 */
	
	@GetMapping("/getFilterLineNames/{stationId}/{start}/{end}")
	public String getFilterLineNames(@PathVariable("stationId") String stationId,
			@PathVariable("start") String start, @PathVariable("end") String end) {
		// 电压等级 线路 变电站
		Date startDate = DateUtil.getDateByString(start + " 00:00:00", DateUtil.pattern_ymdhms);
		Date endDate = DateUtil.getDateByString(end + " 00:00:00", DateUtil.pattern_ymdhms);
		endDate = DateUtil.addDays(endDate, 1);
		if (StringUtils.isEmpty(stationId) || stationId.contains("null")) {
			stationId = null;
		}
		List<ProtectInterruptAlarm> interrupts = pdam.getProtectInterruptAlarmByStationAndDate(stationId,
				startDate, endDate);
		// {lines:map<id,name>,stations:map<id,name>}
		Map<String, String> lineMap = new LinkedHashMap<String, String>();
		Map<String, String> stationMap = new LinkedHashMap<String, String>();
		Map<String, String> lineAllMap = new LinkedHashMap<String, String>();
		Map<String, String> stationAllMap = new LinkedHashMap<String, String>();
		List<Map<String, String>> tempList = new ArrayList<Map<String, String>>();
		List<Map<String, String>> tempListStation = new ArrayList<Map<String, String>>();
		for (int i = 0; i < interrupts.size(); i++) {
			ProtectInterruptAlarm interrupt = interrupts.get(i);
			if (interrupt.getLineId() != null) {
				String lname = lineMap.get(interrupt.getLineId());
				if (lname == null) {
					lineMap.put(interrupt.getLineId(), interrupt.getLineName());
				}
			}
			if (interrupt.getStationId() != null) {
				String sname = stationMap.get(interrupt.getStationId());
				if (sname == null) {
					stationMap.put(interrupt.getStationId(), interrupt.getStationName());
				}
			}
		}
		JSONObject result = new JSONObject();
		tempList = sortMapValue(lineMap, stationId, startDate, endDate, 0);// 0:线路
		if (tempList != null && !tempList.isEmpty() && tempList.size() > 1) {
			lineMap = tempList.get(0);
			lineAllMap = tempList.get(1);
		}
		tempListStation = sortMapValue(stationMap, stationId, startDate, endDate, 1);// 1:变电站
		if (tempListStation != null && !tempListStation.isEmpty() && tempListStation.size() > 1) {
			stationMap = tempListStation.get(0);
			stationAllMap = tempListStation.get(1);
		}
		result.put("lines", lineMap);
		result.put("lineAll", lineAllMap);
		result.put("stations", stationMap);
		result.put("stationsAll", stationAllMap);
		return result.toString();
	}

	/**
	 * 查询线路的故障条数
	 *
	 * @param oldMap
	 * @param stationId
	 * @param startDate
	 * @param endDate
	 * @param name
	 * @return 返回一个有序的map<String,String>
	 */
	private List<Map<String, String>> sortMapValue(Map<String, String> oldMap, String stationId,
			Date startDate, Date endDate, int name) {
		Map<String, String> Map = new LinkedHashMap<String, String>();
		Map<String, String> MapAll = new LinkedHashMap<String, String>();
		Map<String, Integer> temp = new LinkedHashMap<String, Integer>();
		Map<String, Integer> sortTemp = new LinkedHashMap<String, Integer>();
		for (String key : oldMap.keySet()) {
			long count = 0;
			ArrayList<Object> param = getSqlAndParam(name, stationId, startDate, endDate, key);
			Object[] whereArgs = (Object[]) param.get(0);
			String sql = (String) param.get(1);
			count = dao.count(sql, whereArgs, ProtectInterruptAlarm.class);
			Integer i = (int) count;
			temp.put(key, i);
		}
		sortTemp = sortMapByValue(temp);
		for (String key : sortTemp.keySet()) {
			String value = oldMap.get(key) + "(" + sortTemp.get(key) + ")";
			Map.put(key, value);
			temp.remove(key);
		}
		for (String key : temp.keySet()) {
			String value = oldMap.get(key);
			MapAll.put(key, value);
		}
		if (Map.size() > 9) {
			Map.put("qita", "其他");
		}
		List<Map<String, String>> tempList = new ArrayList<Map<String, String>>();
		tempList.add(0, Map);
		tempList.add(1, MapAll);
		return tempList;
	}

	private ArrayList<Object> getSqlAndParam(int name, String stationId, Date startDate, Date endDate,
			String key) {
		ArrayList<Object> list = new ArrayList<Object>();
		Object[] whereArgs = null;
		String sql = " eventStart>=? AND eventStart<=?  ";
		list.add(startDate);
		list.add(endDate);
		if (name == 0) { // 线路
			sql += " AND lineId=?";
			list.add(key);
			if (StringUtils.isNotEmpty(stationId)) {
				sql += " AND lineId=?";
				list.add(stationId);
			}
		} else {// 变电站
			sql += " AND stationId=?";
			list.add(key);
		}
		whereArgs = list.toArray();
		list.clear();
		list.add(whereArgs);
		list.add(sql);
		return list;
	}

	private Map<String, Integer> sortMapByValue(Map<String, Integer> map) {
		// sortMap,最终有顺序的map，id、num
		Map<String, Integer> sortMap = new LinkedHashMap<String, Integer>();
		List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
		Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
			// 降序排序
			@Override
			public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
				return o2.getValue().compareTo(o1.getValue());
			}

		});
		if (list.size() > 10) {
			for (int i = 0; i < 10; i++) {
				Map.Entry<String, Integer> mapping = list.get(i);
				sortMap.put(mapping.getKey(), mapping.getValue());
				// log.info(mapping.getKey() + ":"
				// +mapping.getValue());
			}
		} else if (list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				Map.Entry<String, Integer> mapping = list.get(i);
				sortMap.put(mapping.getKey(), mapping.getValue());
				// log.info(mapping.getKey() + ":"
				// +mapping.getValue());
			}
		}
		return sortMap;
	}
	/**
	 * 保护告警模块-----弹窗使用的保护通道频繁中断 获取本站数据
	 */
	@GetMapping("/getFrequentProtectInterruptAlarmByStationId/{start}/{end}/{param1}/{param2}/{stationId}")
	public String getFrequentProtectInterruptAlarmByStationId(@PathVariable("start") String start,
												   @PathVariable("end") String end,
													@PathVariable("param1") Integer param1,
												   @PathVariable("param2") Integer param2,
													@PathVariable("stationId") String stationId) {
		Date s = DateUtil.getDateByString(start, DateUtil.pattern_ymd);
		Date e = DateUtil.getDateByString(end, DateUtil.pattern_ymd);
		Calendar c = Calendar.getInstance();
		c.setTime(e);
		c.add(Calendar.DAY_OF_YEAR, 1);
		c.add(Calendar.SECOND, -1);
		e = c.getTime();
		List<ProtectDeviceAlarmModel> frequentInterrupts = pdam
				.getFrequentProtectInterruptAlarmByStationAndDate(stationId, s, e, param2, param1 * 60000);
		Collections.sort(frequentInterrupts, new Comparator<ProtectDeviceAlarmModel>() {
			@Override
			public int compare(ProtectDeviceAlarmModel o1, ProtectDeviceAlarmModel o2) {
				return o2.getAlarms().size() - o1.getAlarms().size();
			}
		});
		return JSONArray.fromObject(frequentInterrupts).toString();
	}


	/**
	 * 保护告警模块-----弹窗使用的保护双通道相继异常  获取本站数据
	 */

	@GetMapping("/getFrequentDoubleChannelAlarmByStationId/{start}/{end}/{stationId}")
	public String getFrequentDoubleChannelAlarmByStationId(@PathVariable("start") String start, @PathVariable("end") String end,
												 @PathVariable("stationId") String stationId) {
		JSONArray result = new JSONArray();
		Integer maxTime = Integer.parseInt(pc.get(ParamDesc.FREQUENTLY_DOUBLE_CHANNEL_ALARM_TIME_MAX_GAP)
				.getValue());
		Date s = DateUtil.getDateByString(start, DateUtil.pattern_ymd);
		Date e = DateUtil.getDateByString(end, DateUtil.pattern_ymd);
		Calendar c = Calendar.getInstance();
		c.setTime(e);
		c.add(Calendar.DAY_OF_YEAR, 1);
		c.add(Calendar.SECOND, -1);
		e = c.getTime();
		List<ProtectDeviceAlarmModel> channels = pdam.getFrequentDoubleInterruptAlarmByDate(stationId, s, e);
		// 添加双通道告警附近的频繁告警
		List<ProtectInterruptAlarm> list = pdam.getProtectInterruptAlarmByStationAndDate(stationId, s, e);
		Iterator<ProtectDeviceAlarmModel> it = channels.iterator();
		Iterator<ProtectInterruptAlarm> lit = list.iterator();
		while (it.hasNext()) {
			ProtectDeviceAlarmModel model = it.next();
			List<AbstractProtectAlarm> as = model.getAlarms();
			// 若发生了双通道同时中断，将双通道中断前后半小时内的中断全部放到alarms
			long starttime = as.get(0).getEventStart().getTime() - maxTime;
			long endtime = as.get(as.size() - 1).getEventStart().getTime() + maxTime;
			lit = list.iterator();
			List<AbstractProtectAlarm> frequentAlarms = new ArrayList<>();
			while (lit.hasNext()) {
				AbstractProtectAlarm a = lit.next();
				long t = a.getEventStart().getTime();
				if (a.getLineId() != null && a.getLineId().equals(model.getLineId())
						&& a.getProtectType() != null && a.getProtectType().equals(model.getProtectType())
						&& t > starttime && t < endtime) {
					frequentAlarms.add(a);
				}
			}
			Collections.sort(frequentAlarms, new Comparator<AbstractProtectAlarm>() {
				@Override
				public int compare(AbstractProtectAlarm o1, AbstractProtectAlarm o2) {
					Long t1 = o1.getEventStart().getTime() + o1.getmStartMs();
					Long t2 = o2.getEventStart().getTime() + o2.getmStartMs();
					return t1.compareTo(t2);
				}
			});
			JSONObject o = JSONObject.fromObject(model);
			o.put("frequentAlarms", frequentAlarms);
			result.add(o);
		}
		return result.toString();
	}
}
